package com.tsj.spzx.Interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.tsj.spzx.utils.AuthContextThreadLocalUtil;
import com.tsj.spzx.common.RedisStoredKey;
import com.tsj.spzx.exception.TsjException;
import com.tsj.spzx.model.entity.system.SysUser;
import com.tsj.spzx.model.vo.common.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 在请求处理之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 先判断是不是预检请求
        if(request.getMethod().equals("OPTIONS")){
            // 预检请求放行
            return true;
        }

        // 获取请求头中的token
        String token = request.getHeader("token");
        // 判断token是否为空，如果为空，则抛出异常
        if(StrUtil.isEmpty(token)){
            throw new TsjException(ResultCodeEnum.LOGIN_AUTH);
        }
        // 如果不为null, 从redis中获取用户信息
        String userJson = redisTemplate.opsForValue().get(RedisStoredKey.USER_LOGIN_TOKEN_PREFIX + token);
        if(StrUtil.isEmpty(userJson)){
            throw new TsjException(ResultCodeEnum.LOGIN_AUTH);
        }

        // 将用户信息解析为对象
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        // 用户信息存储到ThreadLocal中
        AuthContextThreadLocalUtil.set(sysUser);

        // 重置redis中token有效时间，即做到 让其在用户最后一次请求 过XX时间后过期
        redisTemplate.expire(RedisStoredKey.USER_LOGIN_TOKEN_PREFIX + token, 30, TimeUnit.MINUTES);

        // 放行
        return true;
    }

    // 在请求处理之后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextThreadLocalUtil.remove();
    }
}
